import sys
import re
import subprocess
import socket
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
 

def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

def get_device(video_list,audio_list):
    cmd = ['ffmpeg', '-list_devices','true', '-f','dshow','-i','dummy']
    process = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8",
                           text=True)
    flag=0
    count=0
    for line in process.stdout:
        _line=line
        if line.startswith("[dshow"): #有效语句
            count+=1
            index = line.find("]")
            if index > 0:
                _line = line[index+2:]
        if _line.startswith("DirectShow video"):
            flag=1 #1:video    2:audio
            count=-1
            continue
        if _line.startswith("DirectShow audio"):   
            flag=2
            count=-1
            continue
        if flag==1 and count%2==0:
            video_list.append(_line[2:len(_line)-2])
        
        if flag==2 and count%2==0:
            audio_list.append(_line[2:len(_line)-2])
    video_list.append("屏幕")
    audio_list.append("None")

class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        self.video_list = [] 
        self.audio_list = []
        get_device(self.video_list,self.audio_list)
        self.initUI()
              
    def initUI(self):        
        self.resize(400, 375)
        self.setWindowTitle('直播设置')
        label1=QLabel(self)
        label1.setText("视频设备：")
        label1.move(38,78)
        self.combo1 = QComboBox(self)
        for i in self.video_list:
            self.combo1.addItem(i)
        self.combo1.move(120, 75)

        label2=QLabel(self)
        label2.setText("音频设备：")
        label2.move(38,153)
        self.combo2 = QComboBox(self)
        for i in self.audio_list:
            self.combo2.addItem(i)
        self.combo2.move(120, 150)

        btn1=QPushButton(self)
        btn1.setText("开始")
        btn1.move(150,200)
        btn1.clicked.connect(self.buttonClicked1)            

        
        btn2=QPushButton(self)
        btn2.setText("停止")
        btn2.move(150,240)
        btn2.clicked.connect(self.buttonClicked2)

        self.label3=QLabel(self)
        self.label3.setText("状态：无推流")
        self.label3.setStyleSheet("color: #b45353; text-shadow:0 0 10px; letter-spacing: 1px; text-align: center;font-size:20pt;")
        self.label3.move(100,300)
        
        self.show()

    def buttonClicked1(self):
        video=self.combo1.currentText()
        audio=self.combo2.currentText()
        ip=get_host_ip()
        if(video=='屏幕' and audio!='None'):
            cmd=['ffmpeg','-f','dshow','-i','audio='+audio,'-f','gdigrab','-video_size','1024x768','-framerate','15','-i','desktop','-pix_fmt','yuv420p','-codec:v','libx264','-bf','0','-g','300','-f','flv','rtmp://'+ip+'/live/test']
        elif(video=='屏幕' and audio=='None'):
            cmd=['ffmpeg','-f','gdigrab','-video_size','1024x768','-framerate','15','-i','desktop','-pix_fmt','yuv420p','-codec:v','libx264','-bf','0','-g','300','-f','flv','rtmp://'+ip+'/live/test']
        elif(video!='屏幕' and audio!='None'):
            cmd=['ffmpeg','-f','dshow','-i','video='+video+':audio='+audio,'-pix_fmt','yuv420p','-codec:v','libx264','-bf','0','-g','300','-f','flv','rtmp://'+ip+'/live/test']
        elif(video!='屏幕' and audio=='None'):
            cmd=['ffmpeg','-f','dshow','-i','video='+video,'-pix_fmt','yuv420p','-codec:v','libx264','-bf','0','-g','300','-f','flv','rtmp://'+ip+'/live/test']
        #cmd=['ffmpeg','-f','dshow','-i','''video=HP Wide Vision HD Camera:audio=麦克风阵列 (Realtek(R) Audio)''','-pix_fmt','yuv420p','-codec:v','libx264','-bf','0','-g','300','-f','flv','rtmp://192.168.0.102:1935/live/test']
        self.process = subprocess.Popen(cmd, shell=False,encoding="utf-8")
        self.label3.setText("状态：推流中")
    
    def buttonClicked2(self):
        self.process.kill()
        self.label3.setText("状态：无推流")


